<template>
  <view class="wifi-main-container">
    <!-- 页面头部区域 -->
    <view class="header">
      <view class="wifi-ssid" v-if="currentWifi">{{ currentWifi }}</view>
      <view class="header-icons">
        <view class="icon-item">•••</view>
        <view class="icon-item record-btn">⚪</view>
      </view>
    </view>
    
    <!-- 主标题区域 -->
    <view class="main-title-area">
      <view class="main-title">共享WiFi精灵</view>
      <view class="main-subtitle">一键连接 轻松上网 免费体验</view>
    </view>
    
    <!-- WiFi信息卡片 -->
    <view class="wifi-card-area" v-if="wifiInfo.ssid">
      <view class="wifi-card">
        <view class="wifi-header">
          <view class="wifi-icon">📶</view>
          <view class="wifi-name">{{ wifiInfo.ssid }}</view>
        </view>
        <button class="connect-btn" @tap="connectWifi" :disabled="connecting">
          {{ connecting ? '连接中...' : '一键连接' }}
        </button>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-area" v-else-if="loading">
      <view class="loading-spinner">⏳</view>
      <view class="loading-text">正在获取WiFi信息...</view>
    </view>
    
    <!-- 错误状态 -->
    <view class="error-area" v-else-if="!loading && !wifiInfo.ssid">
      <view class="error-icon">📡</view>
      <view class="error-text">暂未获取到WiFi信息</view>
      <button class="retry-btn" @tap="loadWifiInfo">重试</button>
    </view>
    

    


    <!-- 协议确认弹窗 -->
    <agreement-modal
      :visible="showAgreementModal"
      @confirm="onAgreementConfirm"
      @close="onAgreementClose"
    ></agreement-modal>
    
    <!-- 自定义TabBar -->
    <custom-tab-bar></custom-tab-bar>
  </view>
</template>

<script>
import { scanSession, getWifiList } from '@/api/wifi/auth'
import AgreementModal from '@/components/agreement-modal/index.vue'
import CustomTabBar from '@/custom-tab-bar/index.vue'

export default {
  name: 'WifiMain',
  components: {
    AgreementModal,
    CustomTabBar
  },
  data() {
    return {
      deviceId: '',
      currentWifi: '腾途传媒-5G', // 当前连接的WiFi名称
      showTestMode: false, // 生产关闭测试模式
      showAgreementModal: false,
      agreementConfirmed: false,
      wifiInfo: {}, // WiFi信息
      loading: false, // 加载状态
      connecting: false // 连接状态
    }
  },
  onLoad(options) {
    console.log('WiFi主页参数：', options)
    
    // 从URL参数或分享链接解析设备ID
    this.deviceId = this.parseDeviceIdFromOptions(options)
    console.log('解析到的deviceId：', this.deviceId)
    
    // 监听扫码事件
    uni.$on('scanDeviceId', this.handleScanDeviceId)
    
    // 如果有设备ID，自动获取WiFi信息
    if (this.deviceId) {
      this.loadWifiInfo()
    }
  },
  
  onShow() {
    // 每次页面显示时检查是否需要刷新WiFi信息
    console.log('首页显示，当前deviceId：', this.deviceId)
  },
  
  onUnload() {
    // 取消监听
    uni.$off('scanDeviceId', this.handleScanDeviceId)
  },
  
  // 分享给好友
  onShareAppMessage(res) {
    console.log('触发分享给好友', res)
    
    // 如果有设备ID，分享时带上设备ID
    if (this.deviceId) {
      return {
        title: `免费WiFi - ${this.currentWifi}`,
        path: `/pages/index?deviceId=${this.deviceId}`,
        imageUrl: '' // 可以设置分享图片，留空使用默认截图
      }
    }
    
    // 默认分享内容
    return {
      title: '共享WiFi精灵 - 一键连接，轻松上网',
      path: '/pages/index',
      imageUrl: ''
    }
  },
  
  // 分享到朋友圈（可选）
  onShareTimeline() {
    console.log('触发分享到朋友圈')
    
    if (this.deviceId) {
      return {
        title: `免费WiFi - ${this.currentWifi}，一键连接`,
        query: `deviceId=${this.deviceId}`,
        imageUrl: ''
      }
    }
    
    return {
      title: '共享WiFi精灵 - 一键连接，轻松上网',
      query: '',
      imageUrl: ''
    }
  },
  methods: {
    
    // 解析页面参数中的设备ID
    parseDeviceIdFromOptions(options) {
      try {
        // 1. 优先从 deviceId 参数获取（分享链接、URL参数）
        if (options.deviceId) {
          console.log('从deviceId参数获取：', options.deviceId)
          return options.deviceId
        }
        
        // 2. 从 scene 参数获取（微信扫一扫二维码、小程序码）
        if (options.scene) {
          console.log('收到scene参数：', options.scene)
          
          // scene参数可能经过URL编码，需要先解码
          let scene = decodeURIComponent(options.scene)
          console.log('解码后的scene：', scene)
          
          // 尝试多种格式解析
          // 格式1: deviceId=xxx
          if (scene.includes('deviceId=')) {
            const match = scene.match(/deviceId=([^&]+)/)
            if (match && match[1]) {
              console.log('从scene提取deviceId（格式1）：', match[1])
              return match[1]
            }
          }
          
          // 格式2: 直接是设备ID（纯文本）
          // 假设设备ID是字母数字组合，如 DEV-001, DEVICE123 等
          if (/^[A-Z0-9-_]+$/i.test(scene)) {
            console.log('scene直接是deviceId（格式2）：', scene)
            return scene
          }
          
          // 格式3: scene=deviceId 或其他分隔符
          const parts = scene.split('=')
          if (parts.length > 1) {
            console.log('从scene分割提取deviceId（格式3）：', parts[1])
            return parts[1]
          }
          
          console.log('无法解析scene，尝试直接使用：', scene)
          return scene
        }
        
        // 3. 从 q 参数获取（扫普通链接二维码）
        if (options.q) {
          console.log('收到q参数：', options.q)
          const url = decodeURIComponent(options.q)
          console.log('解码后的URL：', url)
          
          // 从URL中提取deviceId参数
          if (url.includes('deviceId=')) {
            const match = url.match(/deviceId=([^&]+)/)
            if (match && match[1]) {
              console.log('从q参数URL提取deviceId：', match[1])
              return match[1]
            }
          }
        }
        
        console.log('未找到deviceId参数')
        return ''
      } catch (error) {
        console.error('解析deviceId失败：', error)
        return ''
      }
    },
    
    // 处理扫码获取的设备ID
    handleScanDeviceId(deviceId) {
      console.log('收到扫码设备ID：', deviceId)
      this.deviceId = deviceId
      
      // 清空之前的WiFi信息
      this.wifiInfo = {}
      
      // 加载新的WiFi信息
      this.loadWifiInfo()
    },
    
    // 加载WiFi信息
    async loadWifiInfo() {
      if (!this.deviceId) {
        uni.showToast({
          title: '请扫一扫wifi二维码',
          icon: 'error'
        })
        return
      }
      
      try {
        this.loading = true
        console.log('正在获取WiFi信息，deviceId：', this.deviceId)
        
        const response = await getWifiList(this.deviceId)
        console.log('WiFi信息响应：', response)
        
        if (response.code === 200 && response.data) {
          // 只取第一个WiFi信息
          const wifiData = response.data
          this.wifiInfo = {
            ssid: wifiData.ssid || '未知WiFi',
            password: wifiData.password || '',
            isSecure: wifiData.isSecure !== false,
            securityType: wifiData.securityType,
            frequency: wifiData.frequency,
            signalStrength: wifiData.signalStrength
          }
          
          // 更新当前WiFi名称
          if (wifiData.deviceName) {
            this.currentWifi = wifiData.deviceName
          } else if (wifiData.ssid) {
            this.currentWifi = wifiData.ssid
          }
          
          console.log('WiFi信息加载成功：', this.wifiInfo)
        } else {
          throw new Error(response.msg || '获取WiFi信息失败')
        }
      } catch (error) {
        console.error('获取WiFi信息失败：', error)
        uni.showToast({
          title: error.message || '获取WiFi信息失败',
          icon: 'error'
        })
        this.wifiInfo = {}
      } finally {
        this.loading = false
      }
    },
    
    // 连接WiFi - 跳转到广告页面
    connectWifi() {
      if (this.connecting || !this.wifiInfo.ssid) return
      
      if (!this.deviceId) {
              uni.showToast({
          title: '设备信息缺失',
          icon: 'error'
        })
        return
      }
      
      try {
        console.log('跳转到广告页面，WiFi信息：', this.wifiInfo)
        
        // 将WiFi信息编码后传递给广告页面
        const wifiInfoStr = encodeURIComponent(JSON.stringify(this.wifiInfo))
        
        // 跳转到广告页面
        uni.navigateTo({
          url: `/pages/ad-video/index?deviceId=${this.deviceId}&wifiInfo=${wifiInfoStr}&ssid=${this.wifiInfo.ssid}`
        })
        
      } catch (error) {
        console.error('跳转广告页面失败：', error)
        uni.showToast({
          title: '跳转失败，请重试',
          icon: 'error'
        })
      }
    },
    
    // 检查协议并获取WiFi信息
    checkAgreementAndGetWifi() {
      // 检查是否已确认协议
      const agreementKey = `agreement_confirmed_${this.deviceId}`
      const confirmed = uni.getStorageSync(agreementKey)
      
      if (confirmed) {
        this.agreementConfirmed = true
        this.getWifiInfoAndNavigate()
      } else {
        this.showAgreementModal = true
      }
    },
    
    // 获取WiFi信息并跳转到WiFi列表页面
    async getWifiInfoAndNavigate() {
      if (!this.deviceId) {
        uni.showToast({
          title: '请使用小程序扫一扫wifi二维码',
          icon: 'error'
        })
        return
      }
      
      try {
        uni.showLoading({ title: '获取WiFi信息...' })
        
        // 调用WiFi信息接口
        const response = await getWifiList(this.deviceId)
        
        if (response.code === 200 && response.data) {
          // 获取成功，跳转到WiFi列表页面
          uni.navigateTo({
            url: `/pages/wifi/list/index?deviceId=${this.deviceId}&direct=true`
          })
        } else {
          throw new Error(response.msg || '获取WiFi信息失败')
        }
      } catch (error) {
        console.error('获取WiFi信息失败：', error)
        uni.showToast({
          title: error.message || '获取WiFi信息失败',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 检查协议并开始认证
    checkAgreementAndStart() {
      // 检查是否已确认协议
      const agreementKey = `agreement_confirmed_${this.deviceId}`
      const confirmed = uni.getStorageSync(agreementKey)
      
      if (confirmed) {
        this.agreementConfirmed = true
        this.startWifiAuth()
      } else {
        this.showAgreementModal = true
      }
    },
    
    // 协议确认处理
    onAgreementConfirm(data) {
      console.log('用户确认协议：', data)
      this.showAgreementModal = false
      this.agreementConfirmed = true
      
      // 保存协议确认状态
      const agreementKey = `agreement_confirmed_${this.deviceId}`
      uni.setStorageSync(agreementKey, {
        confirmed: true,
        timestamp: data.timestamp,
        deviceId: this.deviceId
      })
      
      // 获取WiFi信息并跳转
      this.getWifiInfoAndNavigate()
    },
    
    // 协议关闭处理
    onAgreementClose() {
      this.showAgreementModal = false
      uni.showToast({
        title: '需要同意协议才能使用',
        icon: 'none'
      })
    },
    
    // 开始WiFi认证流程（保留原有功能）
    async startWifiAuth() {
      if (!this.deviceId) {
        uni.showToast({
          title: '请扫一扫wifi二维码',
          icon: 'error'
        })
        return
      }
      
      try {
        uni.showLoading({ title: '初始化...' })
        
        // 调用扫码接口获取会话
        const response = await scanSession(this.deviceId)
        
        if (response.code === 200 && response.data) {
          const sessionId = response.data.sessionId
          
          // 跳转到WiFi列表页面
          uni.navigateTo({
            url: `/pages/wifi/list/index?deviceId=${this.deviceId}&sessionId=${sessionId}`
          })
        } else {
          throw new Error(response.msg || '获取会话失败')
        }
      } catch (error) {
        console.error('启动认证流程失败：', error)
        uni.showToast({
          title: error.message || '初始化失败',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wifi-main-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  position: relative;
  overflow: hidden;
  padding-bottom: 160rpx; /* 为自定义tabBar留出空间 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 60rpx 40rpx 20rpx;
  color: #fff;
}

.wifi-ssid {
  font-size: 32rpx;
  font-weight: 500;
}

.header-icons {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.icon-item {
  font-size: 36rpx;
}

.record-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
}

.main-title-area {
  text-align: center;
  padding: 100rpx 40rpx 80rpx;
  color: #fff;
}

.main-title {
  font-size: 64rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.main-subtitle {
  font-size: 28rpx;
  opacity: 0.9;
  line-height: 1.6;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 30rpx;
  padding: 16rpx 40rpx;
  display: inline-block;
  background: rgba(255, 255, 255, 0.1);
}

/* WiFi卡片区域 */
.wifi-card-area {
  padding: 0 40rpx;
  margin-bottom: 60rpx;
}

.wifi-card {
  background: #fff;
  border-radius: 40rpx;
  width: 86%;
  max-width: 640rpx;
  margin: 0 auto;
  padding: 40rpx 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.wifi-header {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.wifi-icon {
  font-size: 60rpx;
  margin-right: 16rpx;
  color: #52c41a;
}

.wifi-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.connect-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #ff9a00 0%, #ff6b00 100%);
  border: none;
  border-radius: 50rpx;
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 6rpx 20rpx rgba(255, 107, 0, 0.4);
  
  &::after {
    border: none;
  }
  
  &:disabled {
    opacity: 0.6;
  }
}

/* 加载状态 */
.loading-area {
  text-align: center;
  padding: 60rpx 40rpx;
  color: #fff;
}

.loading-spinner {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 32rpx;
  opacity: 0.9;
}

/* 错误状态 */
.error-area {
  text-align: center;
  padding: 60rpx 40rpx;
  color: #fff;
}

.error-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  opacity: 0.8;
}

.error-text {
  font-size: 32rpx;
  margin-bottom: 30rpx;
  opacity: 0.9;
}

.retry-btn {
  width: 200rpx;
  height: 70rpx;
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.6);
  border-radius: 35rpx;
  color: #fff;
  font-size: 28rpx;
  
  &::after {
    border: none;
  }
}

.test-area {
  text-align: center;
  margin-bottom: 40rpx;
}

.test-btn {
  width: 200rpx;
  height: 60rpx;
  background: transparent;
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.5);
  border-radius: 30rpx;
  font-size: 24rpx;
  
  &::after {
    border: none;
  }
}


</style>
